package com.huopaolan.yohuoshop.Mvp.View.Fragment;

import android.content.Intent;
import android.graphics.Color;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.RecyclerView.OnScrollListener;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.Window;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.Toast;

import com.ccmit.zxinglibrary.activity.CaptureActivity;
import com.chad.library.adapter.base.BaseQuickAdapter;
import com.huopaolan.lib_core.Base.BaseFragment;
import com.huopaolan.yohuoshop.Adapter.HomeCategoryTabAdapter;
import com.huopaolan.yohuoshop.Adapter.HomeGoodsAdapter;
import com.huopaolan.yohuoshop.Adapter.HomeRecommendAdapter;
import com.huopaolan.yohuoshop.Bean.HomeBannerEntity;
import com.huopaolan.yohuoshop.Bean.HomeGoodsEntity;
import com.huopaolan.yohuoshop.Bean.HomeRecommendEntity;
import com.huopaolan.yohuoshop.Di.Compont.DaggerHomeFragmentCompont;
import com.huopaolan.yohuoshop.Di.Modules.HomeFragmentModules;
import com.huopaolan.yohuoshop.Listener.HomeBannerImageLoader;
import com.huopaolan.yohuoshop.Mvp.Contract.HomeFragmentContract;
import com.huopaolan.yohuoshop.Mvp.Presenter.HomeFragmentPresenter;
import com.huopaolan.yohuoshop.Mvp.View.Activity.CommodityDetailsActivity;
import com.huopaolan.yohuoshop.Mvp.View.Activity.HomeActivity;
import com.huopaolan.yohuoshop.NetWork.API;
import com.huopaolan.yohuoshop.R;
import com.jeremyfeinstein.slidingmenu.lib.SlidingMenu;
import com.jwenfeng.library.pulltorefresh.BaseRefreshListener;
import com.jwenfeng.library.pulltorefresh.PullToRefreshLayout;
import com.youth.banner.Banner;
import com.youth.banner.BannerConfig;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.util.ArrayList;
import java.util.List;

import static android.app.Activity.RESULT_OK;

public class HomeFragment extends BaseFragment<HomeFragmentPresenter> implements HomeFragmentContract.HomeFragmentIView, BaseRefreshListener, OnClickListener {
    private View bannerView, categoryView;
    private ImageView imageView, iv_home_navbar_qrcode;
    private PullToRefreshLayout pullToRefreshLayout;
    private RecyclerView rv_home_fragment, rv_home_top, rv_home_tab, rv_home_recommend;
    private LinearLayout home_top;
    private Banner banner;
    private HomeRecommendAdapter recommendAdapter;
    private HomeCategoryTabAdapter tabAdapter, topAdapter;
    private HomeGoodsAdapter goodsAdapter;

    private int bannerHeight = 0;
    private int categoryHeight = 0;
    private int totalY = 0;

    @Override
    public View createView(LayoutInflater inflater) {
        return inflater.inflate(R.layout.fragment_home, null);
    }

    @Override
    public void initView(View view) {
        iv_home_navbar_qrcode = view.findViewById(R.id.iv_home_navbar_qrcode);
        iv_home_navbar_qrcode.setOnClickListener(this);
        //初始化刷新控件
        pullToRefreshLayout = view.findViewById(R.id.home_pulllayout);
        pullToRefreshLayout.setRefreshListener(this);
        //初始化fragment关联的控件
        rv_home_fragment = view.findViewById(R.id.home_recycler);
        home_top = view.findViewById(R.id.ll_home_top_bg);
        rv_home_tab = view.findViewById(R.id.home_tab);
        imageView = view.findViewById(R.id.iv_home_fragment_sliding_menu_left);
        imageView.setOnClickListener(this);
        //初始化banner控件
        bannerView = View.inflate(getActivity(), R.layout.item_home_banner, null);
        banner = bannerView.findViewById(R.id.ban_home_head);
        //初始化category控件
        categoryView = View.inflate(getActivity(), R.layout.item_home_recommend, null);
        rv_home_top = categoryView.findViewById(R.id.rv_home_goods_category_tab);
        //初始化推荐values控件
        rv_home_recommend = categoryView.findViewById(R.id.rv_recommend_url);
        //测量banner以及category高度
        bannerView.measure(0, 0);
        categoryView.measure(0, 0);
        //获取measure高度
        bannerHeight = bannerView.getMeasuredHeight();
        categoryHeight = categoryView.getMeasuredHeight();
        //添加适配器相关
        //recommend推荐配置
        LinearLayoutManager recommend_layout = new LinearLayoutManager(getActivity());
        recommend_layout.setOrientation(LinearLayoutManager.HORIZONTAL);
        rv_home_recommend.setLayoutManager(recommend_layout);
        recommendAdapter = new HomeRecommendAdapter(R.layout.item_home_recommend_item);
        rv_home_recommend.setAdapter(recommendAdapter);
        //tabAdapter配置
        LinearLayoutManager tab_layout = new LinearLayoutManager(getActivity());
        tab_layout.setOrientation(LinearLayoutManager.HORIZONTAL);
        rv_home_top.setLayoutManager(tab_layout);
        topAdapter = new HomeCategoryTabAdapter(R.layout.item_home_goods_title);
        rv_home_top.setAdapter(topAdapter);
        //topAdapter配置
        LinearLayoutManager top_tab_layout = new LinearLayoutManager(getActivity());
        top_tab_layout.setOrientation(LinearLayoutManager.HORIZONTAL);
        rv_home_tab.setLayoutManager(top_tab_layout);
        tabAdapter = new HomeCategoryTabAdapter(R.layout.item_home_goods_title);
        rv_home_tab.setAdapter(tabAdapter);
        //推荐values配置
        //rv_home_recommend.set
        //homeAdapter配置
        GridLayoutManager gridLayoutManager = new GridLayoutManager(getActivity(), 2, GridLayoutManager.VERTICAL, false);
        rv_home_fragment.setLayoutManager(gridLayoutManager);
        rv_home_fragment.addOnScrollListener(new HomeListener());
        goodsAdapter = new HomeGoodsAdapter(R.layout.item_home_goods);
        //添加头布局
        goodsAdapter.addHeaderView(bannerView, 0);
        goodsAdapter.addHeaderView(categoryView, 1);
        rv_home_fragment.setAdapter(goodsAdapter);
        topAdapter.setOnItemClickListener(new BaseQuickAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(BaseQuickAdapter adapter, View view, int position) {
                if (goodsAdapter.getData() == null) {
                    return;
                }
                goodsAdapter.getData().clear();
                p.refresh(topAdapter.getData().get(position).category_id);
            }
        });
        tabAdapter.setOnItemClickListener(new BaseQuickAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(BaseQuickAdapter adapter, View view, int position) {
                if (goodsAdapter.getData() == null) {
                    return;
                }
                goodsAdapter.getData().clear();
                p.refresh(tabAdapter.getData().get(position).category_id);
            }
        });
        goodsAdapter.setOnItemClickListener(new BaseQuickAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(BaseQuickAdapter adapter, View view, int position) {
                startActivity(new Intent(getActivity(), CommodityDetailsActivity.class));
            }
        });
    }

    @Override
    public void onStart() {
        Window window = getActivity().getWindow();
        window.setStatusBarColor(Color.BLACK);
        super.onStart();
    }

    @Override
    public void initData() {
        p.requestAll();
    }

    @Override
    public void setUpDagger() {
        DaggerHomeFragmentCompont.builder()
                .homeFragmentModules(new HomeFragmentModules(this))
                .build().inject(this);
    }

    @Override
    public void bannerSuccess(HomeBannerEntity entity) {
        if (entity == null) {
            return;
        }
        Log.d("HPL", "HomeBannerEntity" + entity.values.size());

        List<String> strings = new ArrayList<>();
        for (HomeBannerEntity.Values values : entity.values) {
            Log.d("Values", "" + API.BaseUrl + values.recommend_url);
            strings.add(API.BaseUrl + values.recommend_url);
        }
        banner.setImages(strings);
        banner.isAutoPlay(true);
        banner.setIndicatorGravity(BannerConfig.CENTER);
        banner.setDelayTime(1 * 1500);
        banner.setBannerStyle(BannerConfig.CIRCLE_INDICATOR);
        banner.setImageLoader(new HomeBannerImageLoader());
        banner.start();
    }

    @Override
    public void recommendSuccess(HomeRecommendEntity entity) {
        if (entity == null) {
            return;
        }
        recommendAdapter.addData(entity.recommend);
        tabAdapter.addData(entity.category);
        topAdapter.addData(entity.category);
    }

    @Override
    public void goodsSuccess(HomeGoodsEntity entity) {
        if (entity == null) {
            return;
        }
        Log.d("HPL", "HomeGoodsEntity" + entity.values.size());
        if (page == 1) {
            goodsAdapter.setNewData(entity.values);
        } else {
            goodsAdapter.setNewData(entity.values);
        }
    }

    @Override
    public void showDialog() {

    }

    @Override
    public void hideDialog() {

    }

    @Override
    public void refresh() {
        goodsAdapter.getData().clear();
        p.requestAll();
        pullToRefreshLayout.finishRefresh();
    }

    @Override
    public void loadMore() {
        p.loadMore();
        pullToRefreshLayout.finishLoadMore();
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.iv_home_fragment_sliding_menu_left:
                HomeActivity.slidingMenu.showMenu();
                break;
            case R.id.iv_home_navbar_qrcode:
                //开启ZXing提供的扫码界面
                Intent intent = new Intent(getActivity(), CaptureActivity.class);
                startActivityForResult(intent, 100);
                break;
        }
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (100 == requestCode && RESULT_OK == resultCode) {
            Bundle bund = data.getExtras();
            String result = bund.getString("result");
        }
    }

    //滑动监听
    private class HomeListener extends OnScrollListener {
        @Override
        public void onScrolled(@NonNull RecyclerView recyclerView, int dx, int dy) {
            super.onScrolled(recyclerView, dx, dy);
            totalY += dy;
            float alpha = (float) totalY / (float) bannerHeight;
            //alpha 0-1;
            if (alpha > 1)
                alpha = 1;
            if (alpha <= 0)
                alpha = 0;
            home_top.setAlpha(alpha);
            GridLayoutManager manager = (GridLayoutManager) recyclerView.getLayoutManager();
            int position = manager.findLastVisibleItemPosition();
            if (position >= 6) {
                rv_home_tab.setVisibility(View.VISIBLE);
            } else {
                rv_home_tab.setVisibility(View.GONE);
            }
        }
    }
}
